/**
 * http配置
 */
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import router from './common/index';
import store from './store'


// 超时时间
// axios.defaults.timeout = 5000

//http request 请求拦截器，有token值则配置上token值
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {  // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加
      config.headers.token = `${token}`;
      config.headers.spreadType = 'CASH_LOAN';
      //这里主要是为了兼容IE9
      var browser = navigator.appName;
      var b_version = navigator.appVersion;
      if (browser == 'Netscape' && b_version.indexOf(';') < 0) {  //火狐
      } else {
        if (b_version.indexOf(';') < 0) {
          return config;
        }
        var version = b_version.split(";");
        var trim_Version = version[1].replace(/[ ]/g, "");
        if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE9.0") {
          if (config.url.indexOf('?') > 0) {
            config.url = config.url + "&token=" + JSON.parse(token).value;
          }
          else {
            config.url = config.url + "?token=" + JSON.parse(token).value;
          }
        }
      }
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });
// http response 拦截器 ,拦截401状态（token过期），重新登录
axios.interceptors.response.use(
  response => {
    console.log(response);
    const code = response.data.code
    switch (code){
      case 207:
        localStorage.removeItem('token');
        store.commit('changeUserTel','');
        store.commit('changeUserToken','');
        router.push('/login');
        response.data.msg = '登录失效，请重新登录';
        return response;
      default:
        return response;
    }


  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          localStorage.removeItem('token');
          store.commit('changeUserTel','');
          store.commit('changeUserToken','');
          router.push('/login')
      }
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  });
export default axios
